/**
 * Created by wenguangjia on 2017/4/17.
 */
(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('levelProtectionController', levelProtectionController);
    levelProtectionController.$inject = ['$scope', 'searchService'];
    function levelProtectionController($scope, searchService) {
        $scope.param={type:"1",startTime:null,endTime:getToday11Clock(),partition:null,area:null};
        $scope.date_Config = {
            start: "year",
            depth: "minute",
            format: "yyyy-MM-dd"
        };
        var isQuery=false;
        $scope.query=function(){
            isQuery=true;
            generate();
            $scope.gridMainOptions.dataSource.read();
        };
        $scope.data={
            "query": {
                "bool": {
                    "filter": [
                        { "term": { "category": "EPES" } },
                        { "term": { "key1.raw": "LOGIN_FAIL" } }
                    ]
                }
            },
            "aggs": {
                "log": {
                    "terms": {
                        "field": "uid",
                        "order": { "_count": "desc" },
                        "size":0
                    },
                    "aggs": {
                        "dates": {
                            "date_histogram": {
                                "field": "@timestamp",
                                "interval": "day",
                                "min_doc_count": 5
                            }
                        }
                    }
                }
            }
        };
        //生成参数格式
        function generate(){
            $scope.data={
                "query": {
                    "bool": {
                        "filter": [
                            { "term": { "category": "EPES" } }
                        ]
                    }
                },
                "aggs": {
                    "log": {
                        "terms": {
                            "field": "uid",
                            "order": { "_count": "desc" },
                            "size":0
                        },
                        "aggs": {
                            "dates": {
                                "date_histogram": {
                                    "field": "@timestamp",
                                    "interval": "day",
                                    "min_doc_count": 5
                                }
                            }
                        }
                    }
                }
            };
            switch ($scope.param.type){
                case "1":
                    $scope.data.query.bool.filter.push({ "term": { "key1.raw": "LOGIN_FAIL" } });
                    break;
                case "2":
                    $scope.data.query.bool.filter.push({ "term": { "key1.raw": "LOGIN_FAIL" } });
                    $scope.data.aggs.log.aggs.dates.date_histogram.interval="month";
                    $scope.data.aggs.log.aggs.dates.date_histogram.min_doc_count=10;
                    break;
                case "3":
                    $scope.data.query.bool.filter.push({ "term": { "key1.raw": "LOGIN_SUCCESS" } });
                    $scope.data.aggs.log.aggs.dates.date_histogram.interval="day";
                    $scope.data.aggs.log.aggs.dates.date_histogram.min_doc_count=20;
                    break;
                case "4":
                    $scope.data.query.bool.filter.push({ "term": { "key1.raw": "LOGIN_SUCCESS" } });
                    $scope.data.aggs.log.aggs.dates.date_histogram.interval="month";
                    $scope.data.aggs.log.aggs.dates.date_histogram.min_doc_count=500;
                    break;
                case "5":
                    $scope.data.query.bool.filter.push({ "term": { "key1.raw": "ACCESSFORM" } });
                    $scope.data.aggs.log.aggs.dates.date_histogram.interval="day";
                    $scope.data.aggs.log.aggs.dates.date_histogram.min_doc_count=100;
                    break;
                case "6":
                    $scope.data.query.bool.filter.push({ "term": { "key1.raw": "ACCESSFORM" } });
                    $scope.data.aggs.log.aggs.dates.date_histogram.interval="month";
                    $scope.data.aggs.log.aggs.dates.date_histogram.min_doc_count=2000;
                    break;
                default:break;
            };
            if($scope.param.startTime!=null&&$scope.param.endTime==null){
                var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime} } };
                $scope.data.query.bool.filter.push(arrayObj);
            }else if($scope.param.startTime==null&&$scope.param.endTime!=null){
                var arrayObj={ "range": { "@timestamp":  {"lt" : $scope.param.endTime} } };
                $scope.data.query.bool.filter.push(arrayObj);
            }else if($scope.param.startTime!=null&&$scope.param.endTime!=null){
                var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                $scope.data.query.bool.filter.push(arrayObj);
            }
            if($scope.param.partition!=undefined && $scope.param.partition!=null && $scope.param.partition!=""){
                var arrayObj={"term":{"partition":$scope.param.partition}};
                $scope.data.query.bool.filter.push(arrayObj);
            }
        }
        $scope.gridMainOptions = {
            selectable: "row",
            sortable: true,
            resizable: true,
            columnMenu: true,
            // pageable: {
            //     refresh: true,
            //     pageSizes: true,
            // }
        };
        $scope.gridMainOptions.columns = [
            {field: "key", title: "用户名"}
        ];
        $scope.Model = kendo.data.Model.define({
            fields: {
                key_as_string: {validation: {required: true}, type: 'date'},
            }
        });
        $scope.array=[];
        $scope.gridMainOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    searchService.query($scope.data,$scope.param.area).then(
                        function(resp){
                            $scope.array.length=0;
                            var temp=resp.data.aggregations.log.buckets;
                            var datas=[];
                            angular.forEach(temp,function(item){
                               var array2=item.dates.buckets;
                               if(array2.length>0) {
                                   datas.push(item);
                                   angular.forEach(array2, function (k) {
                                       k.key = item.key;
                                   });
                                   $scope.array = $scope.array.concat(array2);
                               }
                            });
                            e.success(datas);
                        }
                    )
                }
            },
            batch: true
        });
        $scope.gridDetailOptions = function (dataItem) {
            return {
                dataSource: {
                    transport: {
                        read: function (e) {
                            e.success($scope.array);
                        },
                    },
                    // pageSize: 20,
                    filter: {field: "key", operator: "eq", value: dataItem.key},
                    batch: true,
                    schema: {
                        model: $scope.Model
                    }
                },
                scrollable: false,
                sortable: true,
                // pageable: true,
                selectable: "row",
                columns: [
                    {field: "key_as_string",title: "时间",format:"{0: yyyy-MM-dd}"},
                    {field: "doc_count", title: "登陆次数"},
                ]
            };
        };
        /**
         * 分区配置
         * @type {string}
         */
        $scope.partition = '全部';
        var partitionSrc="";
        searchService.getPartition({}).then(
            function(resp){
                partitionSrc=resp.data;
                $scope.partitionSource=toTree(resp.data);
            },function(err){}
        );
        $scope.selectShow=function(item){
            if(item==0){
                $scope.param.area=null;
                $scope.param.partition=null;
                $scope.partition="全部";
            }
            angular.forEach(partitionSrc,function(k){
                if(item.ename==k.ename){
                    $scope.param.area=k.code;
                    $scope.param.partition=k.ename;
                    $scope.partition=item.fname+"-"+item.cname;
                }
            });
            $scope.win.close();
        };
    }

})();
